package com.kgc.sbt.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.kgc.sbt.api.RushBApi;
import com.kgc.sbt.beans.OrderAll;
import com.kgc.sbt.beans.OrderDetail;
import com.kgc.sbt.beans.OrderMain;
import com.kgc.sbt.mapper.OrderDetailMapper;
import com.kgc.sbt.mapper.OrderMainMapper;
import com.kgc.sbt.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created on 2021/8/13.
 * <p>
 * Author : Lcywings
 * <p>
 * Description : 监听生成订单的消息队列，生成订单
 */
@Component
@Slf4j
public class TradeOrderListener {

    @Autowired
    private RedisUtils redisUtils;

    @Reference
    private RushBApi rushBApi;

    @Autowired(required = false)
    private OrderMainMapper orderMainMapper;

    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;


    /**
     * @author : Lcywings
     * @date : 2021/8/13 9:03
     * @acl : true
     * @description : 从生成抢购订单队列中，获取生成订单请求，开始生成订单
     */
    @JmsListener(destination = "buy-limit-create-order-queue")
    public void createTradeOrderFromQueue(String s) {

        log.info("###### 开始生成订单，请求详情：{}", s);
        OrderAll orderAll = JSONObject.parseObject(s, OrderAll.class);

        // 开始生成订单，存入数据库，存入缓存redis中等
        OrderDetail orderDetail = orderAll.getOrderDetail();
        OrderMain orderMain = orderAll.getOrderMain();
        Map<String, String> paramsMap = orderAll.getParamMap();

        // 生成订单成功，修改redis中抢购的订单的状态为1，生成失败或者异常，改为2
        redisUtils.hset(paramsMap.get("userId") + "-" + paramsMap.get("prodId"), "tradeOrderStatus", 1);

        // 订单存入数据库
        orderMainMapper.insert(orderMain);
        orderDetailMapper.insert(orderDetail);

    }
}